import React, { useState, useRef,useEffect } from 'react';
import { message,Form,Card,Tooltip,Popconfirm } from 'antd';
import {
    CloseOutlined,
    PlusOutlined
  } from '@ant-design/icons';
import { connect } from 'dva';
import { del,save } from './service';
import SaleWageForm from './saleWageForm';
import {HasPermission} from '@/components/AuthComponent/HasPermission';
import {HasNoPermission} from '@/components/AuthComponent/HasNoPermission';
const AuthPlus = HasPermission(PlusOutlined);
const AuthDel = HasPermission(CloseOutlined);

const SaleWage = props => {
    const { submitting,dispatch } = props
    const [_saleWageList, setSaleWageList] = useState([]);
    const [form] = Form.useForm();
    useEffect(() => {
      if (dispatch) {
        dispatch({
          type: 'cubeWage/saleWageList',
          payload:{}
        }).then((result)=>{
          setSaleWageList(result)
        })
       }
  }, []);

    /**
     * 保存
     * @param {*} values 
     */
    const onFinish =async (values,item) =>{
      const hide = message.loading('正在保存');
      if(item.id){
        values.id=item.values
      }
      try {
        await save({
          ...values,
          salaryType:2
        });
        hide();
        message.success('保存成功');
        return true;
      } catch (error) {
        hide();
        message.error('保存失败，请重试');
        return false;
      }
    }
    /**
     * 删除
     */
    const delSaleWage = async (item,index) =>{
      if(!item.id||item.id==''){
        _saleWageList.splice(index,1)
        setSaleWageList([..._saleWageList]);
        return;
      }
      const hide = message.loading('正在删除');
      try {
        let result = await del({
          id: item.id,
        });
        hide();
        if(result.code==0){
          message.success('删除成功，即将刷新');
          _saleWageList.splice(index,1)
          setSaleWageList([..._saleWageList]);
          return true;
        }else{
          message.success(result.message);
          return false;
        }
        
      } catch (error) {
        hide();
        message.error('删除失败，请重试');
        return false;
      }
  }
  /**
   * 新增销售提成
   */
  const addSaleWage = () =>{
    setSaleWageList([..._saleWageList,{}])
  }
    return <Card title="销售提成" extra={<Tooltip placement="top" title="增加"><AuthPlus auth={[`wage:sale:add`]} onClick={()=>addSaleWage()}/></Tooltip>}>
    {
      _saleWageList&&_saleWageList.map((item,index)=><Card key={index} type="inner" size="small" style={{marginBottom:32}} title="销售提成" extra={<Popconfirm
        title="确认删除?"
        onConfirm={()=>delSaleWage(item,index)}
      ><AuthDel auth={[`wage:gd:delete`]}/></Popconfirm>}>
      <SaleWageForm onFinish={onFinish} item={item} submitting={submitting}/>
  </Card>)
    }
</Card>
}
export default connect(({ loading,cubeWage }) => ({
    submitting: loading.effects['cubeWage/save']
}))(SaleWage);